<template>
  <div class="max-w-screen-xl mx-auto h-full overflow-y-auto p-2">
    <el-form label-position="top">
      <el-form-item label="批量查询的额外召唤师">
        <div class="flex w-full">
          <el-select
            class="w-80 mr-2"
            v-model="user"
            multiple
            collapse-tags
            clearable
            placeholder="请选择召唤师"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-button type="primary" @click="filterUser">确认</el-button>
        </div>
      </el-form-item>
      <el-form-item label="默认选中召唤师">
        <div class="flex w-full">
          <el-select
            class="w-80 mr-2"
            v-model="selectedUser"
            multiple
            collapse-tags
            clearable
            placeholder="请选择召唤师"
          >
            <el-option
              v-for="item in allUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-button type="primary" @click="filterSelectedUser">确认</el-button>
        </div>
      </el-form-item>
      <div class="mb-2">
        <span class="mr-2">数据合并</span>
        <el-button size="small" type="success" @click="addLine"
          >添加一行</el-button
        >
      </div>
      <div class="text-sm">
        <span class="inline-block w-36 mr-2">源数据</span>
        <span>合并到</span>
      </div>
      <div class="mt-2" v-for="(single, index) in mergeList">
        <el-select
          class="w-36 mr-2"
          v-model="single.source"
          clearable
          placeholder="请选择召唤师"
        >
          <el-option
            v-for="item in allUserOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          class="w-36 mr-2"
          v-model="single.target"
          clearable
          placeholder="请选择召唤师"
        >
          <el-option
            v-for="item in allUserOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="danger" link @click="deleteLine(index)"
          >删除</el-button
        >
      </div>
      <el-button class="mt-2 mb-2" type="primary" @click="saveLine"
        >确认</el-button
      >
      <el-tabs v-model="activeName" class="flex-1">
        <el-tab-pane label="接口账号" name="api"></el-tab-pane>
        <el-tab-pane label="同步账号" name="synchronous"></el-tab-pane>
      </el-tabs>
      <template v-if="activeName === 'api'">
        <el-form-item label="账号">
          <div class="flex w-full">
            <el-input
              class="w-80 mr-2"
              v-model="userInfo.username"
              @input="usernameChange"
              clearable
              placeholder="请输入账号"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="手机号" v-if="registerFlag">
          <div class="flex w-full">
            <el-input
              class="w-80 mr-2"
              v-model="userInfo.phone"
              clearable
              placeholder="请输入手机号"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="邮箱" v-if="registerFlag">
          <div class="flex w-full">
            <el-input
              class="w-80 mr-2"
              v-model="userInfo.email"
              clearable
              placeholder="请输入邮箱"
            ></el-input>
          </div>
        </el-form-item>
        <div class="mt-4 mb-2">过期时间 {{ expireTime }}</div>
        <el-form-item>
          <el-button
            type="primary"
            v-if="!registerFlag"
            @click="registerFlag = true"
            >去注册</el-button
          >
          <el-button type="primary" v-if="registerFlag" @click="register"
            >注册</el-button
          >
          <el-button type="success" @click="loginIN">登录</el-button>
        </el-form-item>
      </template>
      <template v-if="activeName === 'synchronous'">
        <template v-if="syncUsernameLogged">
          <div class="flex items-center">
            <span class="mr-4">欢迎登陆，{{ syncUsernameLogged }}</span>
            <el-button type="danger" :loading="loading" @click="logout"
              >退出</el-button
            >
          </div>
          <div class="flex flex-wrap items-center mt-2 mb-4">
            <div class="mr-4">
              <el-button
                type="primary"
                :icon="Download"
                plain
                :loading="loading"
                @click="synchronous"
                >同步</el-button
              >
            </div>
            <div class="mr-4">
              <el-button
                type="success"
                :icon="UploadFilled"
                plain
                :loading="loading"
                @click="backups"
                >备份</el-button
              >
            </div>
          </div>
        </template>
        <template v-else>
          <el-form-item label="账号">
            <div class="flex w-full">
              <el-input
                class="w-80 mr-2"
                v-model="syncUsername"
                clearable
                placeholder="请输入账号"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="验证码" v-if="captchaBase64">
            <div class="flex w-full">
              <el-input
                class="w-80 mr-2"
                v-model="captcha"
                clearable
                placeholder="请输入验证码"
              ></el-input>
              <img
                class="w-20 h-6"
                :src="captchaBase64"
                @click="queryCaptcha('refreshCaptcha')"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              v-if="!captchaBase64"
              :loading="loading"
              @click="queryCaptcha('createCaptcha')"
              >去注册</el-button
            >
            <el-button
              type="primary"
              :loading="loading"
              v-if="captchaBase64"
              @click="syncRegister"
              >注册</el-button
            >
            <el-button type="success" :loading="loading" @click="syncLoginIN"
              >登录</el-button
            >
          </el-form-item>
        </template>
      </template>
    </el-form>
    <div class="mb-4">
      <el-button type="warning" @click="clearpart">部分清除缓存</el-button>
      <el-button type="danger" @click="clearAll">全部清除缓存</el-button>
    </div>
    <a href="http://www.jddld.com/">大乱斗buff查询</a>
    <br /><br />
    <a href="https://lol.qq.com/gicp/news/423/2/1334/1.html">LOL版本公告</a>
    <div class="mt-4">
      <el-input
        type="textarea"
        :rows="4"
        v-model="storageStr"
        placeholder="本地缓存的数据"
      ></el-input>
    </div>
    <div class="flex flex-wrap items-center mt-2">
      <div class="mr-4">
        <el-button size="small" type="primary" @click="importStorage"
          >导入</el-button
        >
      </div>
      <div class="mr-4">
        <el-button size="small" type="primary" @click="exportStorage"
          >导出</el-button
        >
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onActivated } from 'vue'
import { defaultUser } from '@/utils/area.js'
import { parseTime, getGuid } from '@/utils/auth.js'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import {
  joinUN_USE,
  generate_captcha,
  userLogin,
  profile,
  getBspapp
} from '@/axios/api.js'

onActivated(() => {
  init()
})

function init() {
  initUserOptions()
  initselectedUserOptions()
  initAuth()
  initMergeList()
  initSyncAccount()
}

const user = ref([])
const userOptions = ref([])
const allUserOptions = ref([...defaultUser])
function initUserOptions() {
  // 批量查询增加额外的召唤师
  const userList = localStorage.getItem('userList')
  try {
    if (userList && Array.isArray(JSON.parse(userList))) {
      const userListArr = JSON.parse(userList)
      userOptions.value = userListArr
      allUserOptions.value = [...defaultUser, ...userListArr]
      user.value = userListArr.map(v => v.value)
    }
  } catch (error) {
    console.log('召唤师报错', error)
  }
}

const selectedUser = ref([])
function initselectedUserOptions() {
  // 批量查询增加额外的召唤师
  const selectedUserList = localStorage.getItem('selectedUserList')
  try {
    if (selectedUserList && Array.isArray(JSON.parse(selectedUserList))) {
      const selectedUserArr = JSON.parse(selectedUserList)
      selectedUser.value = selectedUserArr
    }
  } catch (error) {
    console.log('默认召唤师报错', error)
  }
}

function filterUser() {
  console.log('user', user.value)
  console.log('userOptions', userOptions.value)
  const remaining = userOptions.value.filter(v => user.value.includes(v.value))
  localStorage.setItem('userList', JSON.stringify(remaining))
  getStorageStr()
}

function filterSelectedUser() {
  localStorage.setItem('selectedUserList', JSON.stringify(selectedUser.value))
  getStorageStr()
}

// 注册账号
const userInfo = ref({
  username: '',
  phone: '',
  email: ''
})
function usernameChange(val) {
  console.log('账号变化', val, userInfo.value)
  const str = val.slice(2)
  userInfo.value.phone = `135718625${str}`
  userInfo.value.email = `${val}@qq.com`
}

// 注册按钮控制
const registerFlag = ref(false)
function register() {
  joinUN_USE({
    ...userInfo.value,
    password: '123456',
    gender: 1,
    inviteCode: ''
  }).then(res => {
    console.log('注册成功', res)
    if (res?.success === false) {
      ElMessage({
        message: res?.error?.message,
        type: 'error'
      })
    } else {
      loginIN()
    }
  })
}

// 登录

function loginIN() {
  userLogin({
    username: userInfo.value.username,
    password: '123456'
  }).then(res => {
    console.log('登陆后', res)

    if (res?.success) {
      ElMessage({
        message: '登陆成功',
        type: 'success'
      })
      localStorage.setItem('m3-authorization', res.data?.wt)
      getProfile()
    } else {
      ElMessage({
        message: res?.msg,
        type: 'error'
      })
    }
  })
}

const expireTime = ref('')
// 获取用户信息
function getProfile() {
  profile().then(res => {
    console.log('用户信息', res)
    if (res?.success) {
      expireTime.value = parseTime(res?.data?.expireTime)
      localStorage.setItem('authorization', JSON.stringify(res?.data))
      getStorageStr()
    } else {
      uni.showToast({
        title: res?.error?.message,
        icon: 'error'
      })
    }
  })
}

const authObj = ref({})
function initAuth() {
  try {
    const auth = JSON.parse(localStorage.getItem('authorization'))
    if (auth && typeof auth === 'object') {
      authObj.value = auth
      userInfo.value.username = auth.username
      expireTime.value = parseTime(auth?.expireTime)
    }
  } catch (error) {
    console.log('查询登录账号报错', error)
  }
}

// 清除缓存
function clearpart() {
  localStorage.removeItem('singlePlayerRecord')
  localStorage.removeItem('searchLogs')
  localStorage.removeItem('lol')
  localStorage.removeItem('userHistory')
  localStorage.removeItem('userHistoryDetails')
}

function clearAll() {
  localStorage.clear()
}

// 本地缓存的导入和导出
onActivated(() => {
  getStorageStr()
})

const storageStr = ref('')
function getStorageStr() {
  const storageObj = {
    baseUrl: localStorage.getItem('baseUrl'),
    selectedUserList: localStorage.getItem('selectedUserList'),
    'm3-authorization': localStorage.getItem('m3-authorization'),
    authorization: localStorage.getItem('authorization'),
    defaultPage: localStorage.getItem('defaultPage'),
    displayMode: localStorage.getItem('displayMode'),
    searchHistoryLocal: localStorage.getItem('searchHistoryLocal'),
    userList: localStorage.getItem('userList'),
    mergeList: localStorage.getItem('mergeList')
  }
  storageStr.value = JSON.stringify(storageObj)
}

function importStorage() {
  try {
    const storageObj = JSON.parse(storageStr.value)
    Object.keys(storageObj).forEach(key => {
      localStorage.setItem(key, storageObj[key])
    })
    init()
    ElMessage({
      message: '导入成功',
      type: 'success'
    })
  } catch (error) {
    console.log('Error: ', error)
    ElMessage({
      message: '导入失败',
      type: 'error'
    })
  }
}
async function exportStorage() {
  try {
    await navigator.clipboard.writeText(storageStr.value)
    ElMessage({
      message: '复制成功',
      type: 'success'
    })
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage({
      message: '复制失败',
      type: 'error'
    })
  }
}

const mergeList = ref([{ source: '', target: '' }])

function addLine() {
  mergeList.value.push({ source: '', target: '' })
}

function deleteLine(index) {
  mergeList.value.splice(index, 1)
}

function saveLine() {
  localStorage.setItem('mergeList', JSON.stringify(mergeList.value))
  getStorageStr()
}

function initMergeList() {
  const mergeListStr = localStorage.getItem('mergeList')
  try {
    if (mergeListStr && Array.isArray(JSON.parse(mergeListStr))) {
      const mergeListArr = JSON.parse(mergeListStr)
      mergeList.value = mergeListArr
    }
  } catch (error) {
    console.log('合并数据有问题', error)
  }
}

const activeName = ref('api')
// 同步账号
const captchaBase64 = ref('')
const loading = ref(false)

// 获取验证码
function queryCaptcha(action) {
  loading.value = true
  getBspapp({
    action,
    params: {
      deviceId: deviceId.value,
      scene: 'register'
    }
  })
    .then(res => {
      console.log('验证码2', res)
      captchaBase64.value = res?.captchaBase64
    })
    .finally(() => {
      loading.value = false
    })
}

onActivated(() => {
  getDeviceId()
})

const deviceId = ref()
function getDeviceId() {
  let deviceIdStr = localStorage.getItem('deviceId')
  if (!deviceIdStr) {
    deviceIdStr = getGuid()
    localStorage.setItem('deviceId', deviceIdStr)
  }
  deviceId.value = deviceIdStr
}

// 同步账号登录
const syncUsername = ref('')
const syncUsernameLogged = ref('')
const captcha = ref('')

function initSyncAccount() {
  syncUsernameLogged.value = localStorage.getItem('syncUserName')
}
// 注册
function syncRegister() {
  loading.value = true
  getBspapp({
    action: 'register',
    params: {
      captcha: captcha.value,
      deviceId: deviceId.value,
      id: deviceId.value,
      username: syncUsername.value,
      password: '123456',
      scene: 'register'
    }
  })
    .then(res => {
      console.log('注册后', res)
      if (res?.result?.code === 0) {
        ElMessage({
          message: '注册成功',
          type: 'success'
        })
        syncUsernameLogged.value = res?.result?.username
        localStorage.setItem('syncToken', res?.result?.token)
        localStorage.setItem('syncUserName', res?.result?.username)
        getStorageStr()
      } else {
        ElMessage({
          message: res?.msg ?? res?.error?.message,
          type: 'error'
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}
// 登录
function syncLoginIN() {
  loading.value = true
  getBspapp({
    action: 'login',
    params: {
      username: syncUsername.value,
      password: '123456'
    }
  })
    .then(res => {
      console.log('登陆后', res)
      if (res?.code === 0) {
        ElMessage({
          message: '登陆成功',
          type: 'success'
        })
        syncUsernameLogged.value = res?.username
        localStorage.setItem('syncToken', res?.token)
        localStorage.setItem('syncUserName', res?.username)
      } else {
        ElMessage({
          message: res?.msg ?? res?.error?.message,
          type: 'error'
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 退出登录
function logout() {
  loading.value = true
  getBspapp({
    action: 'logout',
    uniIdToken: localStorage.getItem('syncToken')
  })
    .then(res => {
      console.log('退出登录', res)
      if (res?.code === 0) {
        ElMessage({
          message: '退出登录成功！',
          type: 'success'
        })
        syncUsernameLogged.value = ''
        localStorage.removeItem('syncToken')
        localStorage.removeItem('syncUserName')
      } else {
        ElMessage({
          message: res?.msg ?? res?.error?.message,
          type: 'error'
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 同步
function synchronous() {
  loading.value = true
  getBspapp({
    action: 'getUserInfo',
    params: {
      field: ['config_data']
    },
    uniIdToken: localStorage.getItem('syncToken')
  })
    .then(res => {
      console.log('同步后', res)
      if (res?.code === 0) {
        const config_data = res?.userInfo?.config_data
        if (config_data) {
          try {
            const storageObj = JSON.parse(config_data)
            Object.keys(storageObj).forEach(key => {
              localStorage.setItem(key, storageObj[key])
            })
            getStorageStr()
            // EventBus.emit('updateOption')
            init()
            ElMessage({
              message: '同步成功',
              type: 'success'
            })
          } catch (error) {
            console.log('Error: ', error)
            ElMessage({
              message: '同步失败',
              type: 'error'
            })
          }
        }
      } else {
        ElMessage({
          message: res?.msg ?? res?.error?.message,
          type: 'error'
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 备份
function backups() {
  loading.value = true
  getBspapp({
    action: 'updateUser',
    params: {
      config_data: storageStr.value
    },
    uniIdToken: localStorage.getItem('syncToken')
  })
    .then(res => {
      console.log('备份', res)
      if (res?.code === 0) {
        ElMessage({
          message: '备份到云端成功！',
          type: 'success'
        })
      } else {
        ElMessage({
          message: res?.msg ?? res?.error?.message,
          type: 'error'
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}
</script>
